#!/usr/bin/env node
'use strict'

const fs = require('fs')
const iconv = require('iconv-lite')
const xlsx = require('node-xlsx')
const ejs = require('ejs')

module.exports = {
  renderFilePromise: (templateFile, data) => {
    return new Promise((resolve, reject) => {
      ejs.renderFile(
        templateFile,
        data,
        {
          compileDebug: true
        },
        (err, str) => {
          if (err) {
            reject(err)
          } else {
            resolve(str)
          }
        }
      )
    })
  },
  readFilePromise: (fileName, encoding) => {
    return new Promise((resolve, reject) => {
      fs.readFile(fileName, (err, data) => {
        if (err) {
          reject(err)
        } else {
          var html = iconv.decode(data, encoding)
          resolve(html)
        }
      })
    })
  },

  readDirPromise: (dicPath, filter) => {
    return new Promise((resolve, reject) => {
      fs.readdir(dicPath, (err, data) => {
        if (err) {
          reject(err)
        } else {
          resolve(data.filter(filter))
        }
      })
    })
  },

  writeFilePromise: (text, filePath, encoding) => {
    return new Promise((resolve, reject) => {
      fs.writeFile(filePath, iconv.encode(text, encoding), err => {
        if (err) {
          reject(err)
        } else {
          resolve(filePath)
        }
      })
    })
  },

  writeExcelPromise: (data, filePath) => {
    return new Promise((resolve, reject) => {
      var buffer = xlsx.build(data)
      fs.writeFile(filePath, buffer, err => {
        if (err) {
          reject(err)
        } else {
          resolve(filePath)
        }
      })
    })
  }
}
